#include "image_loader.h"

#include "singleton.h"
#include "asset_manager.h"
#include <core/file_system.h>

#include <mutex>
#include <stb_image.h>

namespace csugl::il {

    std::function<void(uint8_t *)> MImage::data_deleter = [](uint8_t *img_data) {
        stbi_image_free(img_data);
    };

    bool image_loader::pre_load(const std::string &fileName, bool flip) {
        auto tex_name = fs::get_file_name(fileName);
        if (SGT_Ref_Str_AM(MImage)->get(tex_name))
            return true;
        auto meta_image = MakeRef<MImage>();
        stbi_set_flip_vertically_on_load(flip);
        auto meta_data = stbi_load(fileName.c_str(),
                                   &meta_image->width,
                                   &meta_image->height,
                                   &meta_image->channel, 0);
        if (!meta_data)
            return false;
        meta_image->data = Scope<uint8_t, decltype(MImage::data_deleter)>(
            meta_data, MImage::data_deleter);
        SGT_Ref_Str_AM(MImage)->add(tex_name, meta_image);
        return true;
    }

    Ref<MImage> image_loader::load(const std::string &fileName) {
        return SGT_Ref_Str_AM(MImage)->get(fileName);
    }

}